import * as L from "leaflet";
import Vue from "vue";
import {
    WMTS
} from "./WMTS";
 
import {
    DomUtil
} from "leaflet/dist/leaflet-src.esm";
let VCharts = require("echarts/lib/echarts");
require("echarts/lib/chart/bar");
require("echarts/lib/chart/pie");
// 引入提示框和title组件
require("echarts/lib/component/tooltip");
require("echarts/lib/component/title");
import icon from "leaflet/dist/images/marker-icon.png";
import iconShadow from "leaflet/dist/images/marker-shadow.png";
Vue.config.productionTip = false;
Vue.use(VCharts);
let esri = require("esri-leaflet");
// import
let GeowayMap = function() {
    /**
     * 地图对象
     */
    this.geowayMap = null;
    /**
     *获取地图对象
     **/
    this.getMap = () => this.geowayMap;
    /**
     *编辑图层
     **/
 
    this.editLayer = null;
    // 卷帘
    this.mapSplitControl = null;
    /**
     *获取编辑图层
     */
    this.DRAWING = false; // 是否正在绘制
    this.BarDRAWLAYERS = []; // 测距图层存储
    this.ISMEASURE = true; // 是否是量距
    this.MEASURETOOLTIP; // 量距提示
    this.DRAWMOVEPOLYLINE; // 绘制过程中的折线
    this.DRAWPOLYLINEPOINTS = []; // 绘制的折线的节点集
    this.MEASURERESULT = 0;
    this.DRAWMOVEPOLYGON; // 绘制过程中的面
    this.DRAWPOLYGONPOINTS = []; // 绘制的面的节点集
    this.BarAreaLAYERS = [];
    this.DRAWPOLYGON;
    this.markerGroups = null; //聚合点存放
    this.getEditLayer = () => this.editLayer;
    this.getContainer = function() {
        return this.geowayMap._container;
    };
    // 测距
    this.startDrawLine = function(ISMEASURE) {
        let DRAWPOLYLINE = [];
        let _this = this;
        _this.ISMEASURE = ISMEASURE;
        _this.getContainer().style.cursor = "crosshair";
        _this.MEASURERESULT = 0;
        // _this.geowayMap.getContainer().style.cursor = "crosshair";
        _this.geowayMap.on("mousedown", function(e) {
            _this.DRAWING = true;
            _this.DRAWPOLYLINEPOINTS.push(e.latlng);
            if (_this.DRAWPOLYLINEPOINTS.length > 1 && _this.ISMEASURE) {
                _this.MEASURERESULT += e.latlng.distanceTo(
                    _this.DRAWPOLYLINEPOINTS[_this.DRAWPOLYLINEPOINTS.length - 2]
                );
            }
            DRAWPOLYLINE.addLatLng(e.latlng);
        });
        _this.geowayMap.on("mousemove", function(e) {
            if (_this.DRAWING) {
                if (
                    _this.DRAWMOVEPOLYLINE != undefined &&
                    _this.DRAWMOVEPOLYLINE != null
                ) {
                    _this.editLayer.removeLayer(_this.DRAWMOVEPOLYLINE);
                }
                let prevPoint =
                    _this.DRAWPOLYLINEPOINTS[_this.DRAWPOLYLINEPOINTS.length - 1];
                _this.DRAWMOVEPOLYLINE = new L.Polyline(
                    [prevPoint, e.latlng],
                    shapeOptions
                );
                _this.editLayer.addLayer(_this.DRAWMOVEPOLYLINE);
 
                if (ISMEASURE) {
                    let distance =
                        _this.MEASURERESULT +
                        e.latlng.distanceTo(
                            _this.DRAWPOLYLINEPOINTS[_this.DRAWPOLYLINEPOINTS.length - 1]
                        );
                    _this.MEASURETOOLTIP.updatePosition(e.latlng);
                    _this.MEASURETOOLTIP.updateContent({
                        text: "单击确定点，双击结束！",
                        subtext: "总长：" + (distance / 1000).toFixed(2) + "公里",
                    });
                }
            }
        });
 
        _this.geowayMap.on("dblclick", function(e) {
            _this.getContainer().style.cursor = "";
            if (_this.DRAWING) {
                if (
                    _this.DRAWMOVEPOLYLINE != undefined &&
                    _this.DRAWMOVEPOLYLINE != null
                ) {
                    _this.editLayer.removeLayer(_this.DRAWMOVEPOLYLINE);
                    _this.DRAWMOVEPOLYLINE = null;
                }
 
                if (_this.DRAWPOLYLINEPOINTS.length > 1 && ISMEASURE) {
                    _this.MEASURERESULT += e.latlng.distanceTo(
                        _this.DRAWPOLYLINEPOINTS[_this.DRAWPOLYLINEPOINTS.length - 2]
                    );
 
                    let distanceLabel = L.marker(
                        _this.DRAWPOLYLINEPOINTS[_this.DRAWPOLYLINEPOINTS.length - 1], {
                            icon: new L.divIcon({
                                className: "DistanceLabelStyle",
                                iconAnchor: [-8, 15],
                                html: "<span class='bubbleLabel'><span class='bubbleLabel-bot bubbleLabel-bot-left'></span><span class='bubbleLabel-top bubbleLabel-top-left'></span><span>总长：" +
                                    (_this.MEASURERESULT / 1000).toFixed(2) +
                                    "公里" +
                                    "</span></span>",
                            }),
                        }
                    ).addTo(_this.editLayer);
 
                    _this.BarDRAWLAYERS.push(distanceLabel);
                }
 
                // 移除提示框
                if (_this.MEASURETOOLTIP) {
                    _this.MEASURETOOLTIP.dispose();
                }
                _this.BarDRAWLAYERS.push(DRAWPOLYLINE);
                _this.DRAWPOLYLINEPOINTS = [];
                _this.DRAWING = false;
                _this.ISMEASURE = false;
                _this.geowayMap.off("mousedown");
                _this.geowayMap.off("mousemove");
                _this.geowayMap.off("dblclick");
            }
        });
        let shapeOptions = {
            color: "#F54124",
            weight: 3,
            opacity: 0.8,
            fill: false,
            clickable: true,
        };
        DRAWPOLYLINE = new L.Polyline([], shapeOptions);
        _this.editLayer.addLayer(DRAWPOLYLINE);
        if (_this.ISMEASURE) {
            _this.MEASURETOOLTIP = new L.Tooltip(_this.geowayMap);
        }
    };
    // 测面
    this.startDrawPolygon = function(ISMEASURE) {
        let _this = this;
        _this.ISMEASURE = ISMEASURE;
        _this.MEASURERESULT = 0;
        _this.getContainer().style.cursor = "crosshair";
        _this.geowayMap.on("mousedown", function(e) {
            _this.DRAWING = true;
            _this.DRAWPOLYGONPOINTS.push(e.latlng);
            _this.DRAWPOLYGON.addLatLng(e.latlng);
        });
        _this.geowayMap.on("mousemove", function(e) {
            if (_this.DRAWING) {
                if (
                    _this.DRAWMOVEPOLYGON != undefined &&
                    _this.DRAWMOVEPOLYGON != null
                ) {
                    _this.editLayer.removeLayer(_this.DRAWMOVEPOLYGON);
                }
                let prevPoint =
                    _this.DRAWPOLYGONPOINTS[_this.DRAWPOLYGONPOINTS.length - 1];
                let firstPoint = _this.DRAWPOLYGONPOINTS[0];
                _this.DRAWMOVEPOLYGON = new L.Polygon(
                    [firstPoint, prevPoint, e.latlng],
                    shapeOptions
                );
                _this.editLayer.addLayer(_this.DRAWMOVEPOLYGON);
 
                if (_this.ISMEASURE && _this.DRAWPOLYGONPOINTS.length > 1) {
                    let tempPoints = [];
                    for (let i = 0; i < _this.DRAWPOLYGONPOINTS.length; i++) {
                        tempPoints.push(_this.DRAWPOLYGONPOINTS[i]);
                    }
                    tempPoints.push(e.latlng);
                    let distance = _this.calArea(tempPoints);
                    _this.MEASUREAREATOOLTIP.updatePosition(e.latlng);
                    _this.MEASUREAREATOOLTIP.updateContent({
                        text: "单击确定点，双击结束！",
                        subtext: "总面积：" + (distance / 1000000).toFixed(3) + "平方公里",
                    });
                }
            }
        });
 
        _this.geowayMap.on("dblclick", function(e) {
            _this.getContainer().style.cursor = "";
            if (_this.DRAWING) {
                if (
                    _this.DRAWMOVEPOLYGON != undefined &&
                    _this.DRAWMOVEPOLYGON != null
                ) {
                    _this.editLayer.removeLayer(_this.DRAWMOVEPOLYGON);
                    _this.DRAWMOVEPOLYGON = null;
                }
 
                if (_this.DRAWPOLYGONPOINTS.length > 2 && _this.ISMEASURE) {
                    _this.MEASURERESULT = _this.calArea(_this.DRAWPOLYGONPOINTS);
 
                    let distanceLabel = L.marker(e.latlng, {
                        icon: new L.divIcon({
                            className: "DistanceLabelStyle",
                            iconAnchor: [-8, 15],
                            html: "<span class='bubbleLabel'><span class='bubbleLabel-bot bubbleLabel-bot-left'></span><span class='bubbleLabel-top bubbleLabel-top-left'></span><span>总面积：" +
                                (_this.MEASURERESULT / 1000000).toFixed(3) +
                                "平方公里" +
                                "</span></span>",
                        }),
                    }).addTo(_this.editLayer);
 
                    _this.BarDRAWLAYERS.push(distanceLabel);
                }
 
                // 移除提示框
                if (_this.MEASUREAREATOOLTIP) {
                    _this.MEASUREAREATOOLTIP.dispose();
                }
 
                _this.BarDRAWLAYERS.push(_this.DRAWPOLYGON);
                _this.DRAWPOLYGONPOINTS = [];
                _this.DRAWING = false;
                _this.ISMEASURE = false;
                _this.geowayMap.off("mousedown");
                _this.geowayMap.off("mousemove");
                _this.geowayMap.off("dblclick");
            }
        });
 
        let shapeOptions = {
            color: "#F54124",
            weight: 3,
            opacity: 0.8,
            fill: true,
            fillColor: null,
            fillOpacity: 0.2,
            clickable: true,
        };
        _this.DRAWPOLYGON = new L.polygon([], shapeOptions);
        _this.editLayer.addLayer(_this.DRAWPOLYGON);
        if (_this.ISMEASURE) {
            _this.MEASUREAREATOOLTIP = new L.Tooltip(_this.editLayer);
        }
    };
    // 面积计算
    this.calArea = function(latLngs) {
        let pointsCount = latLngs.length,
            area = 0.0,
            d2r = Math.PI / 180,
            p1,
            p2;
        if (pointsCount > 2) {
            for (let i = 0; i < pointsCount; i++) {
                p1 = latLngs[i];
                p2 = latLngs[(i + 1) % pointsCount];
                area +=
                    (p2.lng - p1.lng) *
                    d2r *
                    (2 + Math.sin(p1.lat * d2r) + Math.sin(p2.lat * d2r));
            }
            area = (area * 6378137.0 * 6378137.0) / 2.0;
        }
        return Math.abs(area);
    };
    // 清除测面、测距
    this.clearMap = function() {
        let _this = this;
        // 关闭测距提示框
        if (_this.MEASURETOOLTIP) {
            _this.MEASURETOOLTIP.dispose();
        }
        // 关闭测面提示框
        if (_this.MEASUREAREATOOLTIP) {
            _this.MEASUREAREATOOLTIP.dispose();
        }
 
        // array exists and is not empty
        if (_this.BarDRAWLAYERS.length > 0) {
            for (let i = 0; i < _this.BarDRAWLAYERS.length; i++) {
                _this.geowayMap.removeLayer(_this.BarDRAWLAYERS[i]);
            }
            _this.BarDRAWLAYERS = [];
        }
        // 清除聚合点
        if (_this.markerGroups) {
            _this.markerGroups.clearLayers();
        }
    };
    /**
     * 初始化地图
     */
    this.initMap = function(mapdiv, cfg) {
        this.mapLayer = null;
        this.editLayer = null;
        this.geowayMap = null;
        this.geowayMap = L.map(mapdiv, {
            crs: cfg.mapInfo.crs,
            zoomControl: true,
            center: cfg.mapInfo.center,
            zoom: cfg.mapInfo.level,
            // minZoom: cfg.mapInfo.minlevel,
            // maxZoom: cfg.mapInfo.maxlevel,
            doubleClickZoom: false,
            // measureControl: true,
            /* fullscreenControl: true,
                  fullscreenControlOptions: { // optional
                    title:"全屏",
                    position: 'topright'
                  } */
            // maxBounds:cfg.mapInfo.maxBounds
        });
        this.initMapLayer();
        this.initManagerLayer();
        this.Switchmap();
        // this.getMapServer(config)
    };
    /**
     *添加辅助图层管理
     */
    this.initManagerLayer = function() {
        // 编辑图层
        this.editLayer = L.featureGroup();
        this.geowayMap.addLayer(this.editLayer);
    };
    /**
     *添加底图图层管理
     */
    this.initMapLayer = function() {
        //编辑图层
        this.mapLayer = L.featureGroup();
        this.geowayMap.addLayer(this.mapLayer);
    };
    /**
     *初始化地图控件
     *map 地图对象
     *config 控件显示配置
     **/
    this.initBaseControls = (config) => {
        if (typeof config === "undefined") config = {};
        // 加载比例尺
        if (!config.hasOwnProperty("IsScale") || config.IsScale == true) {
            L.control.scale().addTo(this.geowayMap);
            L.control
                .zoom({
                    zoomInTitle: "放大",
                    zoomOutTitle: "缩小",
                    position: "topright",
                })
                .addTo(this.geowayMap);
            L.control.mousePosition().addTo(this.geowayMap);
        }
    };
    this.dynamicMapLayerLoadMap = (config) => {
        let envLayer = esri
            .dynamicMapLayer({
                url: config.url,
                opacity: config.opacity,
                f: config.f,
            })
            .addTo(this.editLayer);
        return envLayer;
    };
    /**
     *初始化图层
     *@param layers添加图层数组
     *@param config图层配置信息
     */
    this.addMapLayers = (layers, config) => {
        if (typeof config === "undefined") layers = [];
        for (let count = 0; count < layers.length; count++) {
            let layerinfo = layers[count];
            if (layerinfo.serviceType === "wmts") {
                this.addMapLayer(layerinfo);
            } else {
                L.tileLayer(layerinfo.url, {
                    tileSize: 256,
                    zoomOffset: 1,
                    attribution: layerinfo.attribution,
                    isBaseLayer: layerinfo.isBaseLayer,
                    subdomains: layerinfo.subdomains,
                }).addTo(this.geowayMap);
            }
        }
    };
    /**
     * 添加图层信息
     * @param layerinfo图层信息
     */
    this.addMapLayer = function(layerinfo) {
        let layer = null;
        let visibility =
            typeof layerinfo.visibility === "undefined" ? true : layerinfo.visibility;
        let isBaseLayer =
            typeof layerinfo.isBaseLayer === "undefined" ?
            false :
            layerinfo.isBaseLayer;
        switch (layerinfo.serviceType) {
            case "wmts":
                let style = "default";
                let format =
                    typeof layerinfo.format === "undefined" ?
                    "image/png" :
                    layerinfo.format;
                let layerleName;
                let tilematrixSet =
                    typeof layerinfo.tilematrixSet === "undefined" ?
                    "" :
                    layerinfo.tilematrixSet;
                const matrixIds = [];
                for (let i = 0; i < 15; ++i) {
                    matrixIds[i] = {
                        identifier: "" + (i + 1),
                        topLeftCorner: new L.LatLng(90, -180),
                    };
                }
                layer = new L.TileLayer.WMTS(layerinfo.url, {
                    layer: layerinfo.layer,
                    style: "",
                    tilematrixSet: tilematrixSet,
                    format: format,
                    matrixIds: matrixIds,
                    attribution: layerinfo.attribution,
                });
                break;
        }
        if (layer != null) {
            this.geowayMap.addLayer(layer);
        }
        return layer;
    };
    /**
     * 清除地图上所有图层
     */
    this.removeDrawLayer = () => {
        this.editLayer.clearLayers();
        if (this.mapSplitControl) {
            this.mapSplitControl.remove();
            this.mapSplitControl = null;
        }
    };
    /**
     * 清除地图底图所有图层
     */
    this.removeMapLayer = () => {
        this.mapLayer.clearLayers();
    };
    /**
     * 全幅
     */
    this.fullMap = () => {
        this.geowayMap.setView([37, 102], 3);
    };
 
    /**
     * 放大按钮
     */
    this.zoomOut = () => {
        this.geowayMap.zoomOut();
    };
 
    /**
     * 缩小按钮
     */
    this.zoomIn = () => {
        this.geowayMap.zoomIn();
    };
    /**
     * 绘制矩形
     */
    this.drawRectangle = (fn) => {
        // debugger;
        this.editLayer.clearLayers();
        let rectangle;
        let tmprec;
        let latlngs = [];
        this.geowayMap.dragging.disable();
        this.geowayMap.on("mousedown", (e) => {
            if (typeof tmprec !== "undefined") {
                tmprec.remove();
            }
            // 左上角坐标
            latlngs[0] = e.latlng;
            // 开始绘制，监听鼠标移动事件
            this.geowayMap.on("mousemove", (e) => {
                this.editLayer.clearLayers();
                latlngs[1] = e.latlng;
                // 删除临时矩形
                if (typeof tmprect !== "undefined") {
                    tmprec.remove();
                }
                // 添加临时矩形
                tmprec = L.rectangle(latlngs, this.drawStyleMap.Polygon).addTo(
                    this.editLayer
                );
            });
        });
        this.geowayMap.on("mouseup", (e) => {
            this.editLayer.clearLayers();
            // 矩形绘制完成，移除临时矩形，并停止监听鼠标移动事件
            this.geowayMap.off("mousedown");
            this.geowayMap.off("mousemove");
            this.geowayMap.off("mouseup");
            // 右下角坐标
            latlngs[1] = e.latlng;
            rectangle = L.rectangle(latlngs, this.drawStyleMap.Polygon);
            let result = [];
            result.push(latlngs);
            rectangle.addTo(this.editLayer);
            this.geowayMap.dragging.enable();
            if (fn) {
                // 如果需要获取到当前坐标  使用当前回调
                fn(latlngs);
            }
        });
    };
    /**
     * 绘制多边形
     */
    this.drawPolygon = function(fn) {
        this.editLayer.clearLayers();
        let points = [];
        const polygon = new L.polygon(points);
        this.geowayMap.addLayer(polygon);
        this.geowayMap.on("mousedown", (e) => {
            points.push([e.latlng.lat, e.latlng.lng]);
            this.geowayMap.on("mousemove", (event) => {
                polygon.setLatLngs([...points, [event.latlng.lat, event.latlng.lng]]);
            });
        });
        this.geowayMap.on("dblclick", () => {
            if (points.length) {
                this.geowayMap.off("mousedown");
                this.geowayMap.off("mousemove");
                this.geowayMap.off("dblclick");
                polygon.addTo(this.editLayer);
                if (fn) {
                    fn(points);
                }
            }
        });
    };
 
    /**
     * 绘制线
     */
    this.drawPolyline = () => {
        this.editLayer.clearLayers();
        let rectangle;
        let tmprec;
        let latlngs = [];
        this.geowayMap.dragging.disable();
        this.geowayMap.on("mousedown", (e) => {
            if (typeof tmprec !== "undefined") {
                tmprec.remove();
            }
            // 左上角坐标
            latlngs[0] = e.latlng;
            // 开始绘制，监听鼠标移动事件
            this.geowayMap.on("mousemove", (e) => {
                this.editLayer.clearLayers();
                latlngs[1] = e.latlng;
                // 删除临时矩形
                if (typeof tmprect !== "undefined") {
                    tmprec.remove();
                }
                // 添加临时矩形
                tmprec = L.polyline(latlngs, this.drawStyleMap.Line).addTo(
                    this.editLayer
                );
            });
        });
        this.geowayMap.on("mouseup", (e) => {
            this.editLayer.clearLayers();
            // 矩形绘制完成，移除临时矩形，并停止监听鼠标移动事件
            this.geowayMap.off("mousedown");
            this.geowayMap.off("mousemove");
            this.geowayMap.off("mouseup");
            // 右下角坐标
            latlngs[1] = e.latlng;
            rectangle = L.polyline(latlngs, this.drawStyleMap.Line);
            let result = [];
            result.push(latlngs);
            rectangle.addTo(this.editLayer);
            this.geowayMap.dragging.enable();
        });
    };
    /**
     * 绘制点
     */
    this.drawPoint = () => {
        this.editLayer.clearLayers();
        let rectangle;
        let tmprec;
        let latlngs = [];
        this.geowayMap.dragging.disable();
        this.geowayMap.on("mousedown", (e) => {
            if (typeof tmprec !== "undefined") {
                tmprec.remove();
            }
            // 左上角坐标
            latlngs[0] = e.latlng.lat;
            latlngs[1] = e.latlng.lng;
            // 开始绘制，监听鼠标移动事件
            this.geowayMap.on("mousemove", (e) => {
                this.editLayer.clearLayers();
                // 删除临时矩形
                if (typeof tmprect !== "undefined") {
                    tmprec.remove();
                }
                // 添加临时矩形
                tmprec = L.circle(
                    latlngs, {
                        radius: 1,
                    },
                    this.drawStyleMap.Line
                ).addTo(this.editLayer);
            });
        });
        this.geowayMap.on("mouseup", (e) => {
            this.editLayer.clearLayers();
            // 矩形绘制完成，移除临时矩形，并停止监听鼠标移动事件
            this.geowayMap.off("mousedown");
            this.geowayMap.off("mousemove");
            this.geowayMap.off("mouseup");
            rectangle = L.circle(
                latlngs, {
                    radius: 1,
                },
                this.drawStyleMap.Line
            );
            let result = [];
            result.push(latlngs);
            rectangle.addTo(this.editLayer);
            this.geowayMap.dragging.enable();
        });
    };
 
    /**
     *全局绘制样式配置
     **/
    this.drawStyleMap = {
        Point: {
            pointRadius: 5,
            graphicName: "circle",
            fillColor: "white",
            fillOpacity: 1,
            strokeWidth: 1,
            strokeOpacity: 1,
            strokeColor: "#ed7540",
            strokeLinecap: "round",
        },
        Line: {
            strokeWidth: 3,
            strokeOpacity: 1,
            strokeColor: "#ed7540",
            strokeDashstyle: "longdash",
            strokeLinecap: "butt",
        },
        Polygon: {
            color: "#3388FF",
            fillOpacity: 0.1,
            weight: 2,
        },
    };
    /**
     * 高亮选中图形
     */
    this.initHightPoly = function(
        coordinates,
        style,
        isView,
        onEachFeature,
        type,
        pane
    ) {
        if (type == undefined || type == null) {
            type = "Polygon";
        }
        // let states = [{
        //     type: 'Feature',
        //     properties: { party: 'Republican' },
        //     geometry: {
        //         type: type,
        //         coordinates: coordinates
        //     }
        // }]
        if (pane === null || pane === "" || pane == undefined) {
            pane = "overlayPane";
        }
        let geoJsonLayer = L.geoJson(coordinates, {
            style: style,
            pane: pane,
            onEachFeature: (feature, layer) => {
                if (onEachFeature) {
                    // feature, layer,默认参数
                    // color, style 手动传入参数
                    onEachFeature(feature, layer, style);
                }
            },
        }).addTo(this.editLayer);
        // this.editLayer.fitBounds()
 
        if (isView) {
            let latling = geoJsonLayer.getBounds().getCenter();
            let center = L.latLng(latling.lat, latling.lng);
            let currentZoom = this.getMap().getBoundsZoom(geoJsonLayer.getBounds()); // 缩放比例
            this.getMap().setView(center, currentZoom);
        }
        return geoJsonLayer;
    };
    this.initHightPolyMap = function(coordinates, style, isView, type, pane) {
        if (type == undefined || type == null) {
            type = "Polygon";
        }
        if (pane === null || pane === "" || pane == undefined) {
            pane = "overlayPane";
        }
        let geoJsonLayer = L.geoJson(coordinates, {
            style: style,
            pane: pane,
        }).addTo(this.geowayMap);
        if (isView) {
            let latling = geoJsonLayer.getBounds().getCenter();
            let center = L.latLng(latling.lat, latling.lng);
            let currentZoom = this.getMap().getBoundsZoom(geoJsonLayer.getBounds()); // 缩放比例
            this.getMap().setView(center, currentZoom);
        }
        return geoJsonLayer;
    };
 
    this.addAPolygon = function(geometry) {
        this.editLayer.clearLayers();
        let polygon = geometry.coordinates;
        let polygon1 = [];
        for (let item in polygon) {
            let cor = polygon[item];
            let cor1 = [];
            cor1[0] = cor[1];
            cor1[1] = cor[0];
            polygon1.push(cor1);
        }
        let polygon2 = L.polygon(polygon1, {
            color: "red",
            fillColor: "#f03",
            fillOpacity: 0.2,
        });
        polygon2.addTo(this.editLayer);
    };
 
    // 地图切换
    this.Switchmap = function() {
        this.removeMapLayer();
        this.mapLayer.addLayer(WMTS(config.skyMap1.url, config.skyMap1.opt));
        this.mapLayer.addLayer(WMTS(config.skyMap2.url, config.skyMap2.opt));
    };
    // 切换成地形
    this.TerrainSwitching = function() {
        this.removeMapLayer();
        this.mapLayer.addLayer(
            WMTS(config.skymapTopography1.url, config.skymapTopography1.opt)
        );
        this.mapLayer.addLayer(
            WMTS(config.skymapTopography2.url, config.skymapTopography2.opt)
        );
    };
    // 影像加载  该方法暂时用作初始化地图时候加载   todo...
    this.SwitchingImages = function(config) {
        // this.removeMapLayer();
        //   如果是wmts 则用wmts方式加载
        if (config.type == "WMTS") {
            var matrixIds = [];
            for (var i = config.blc; i < 21; ++i) {
                matrixIds[i] = {
                    identifier: "" + (i + config.identifier),
                    topLeftCorner: new L.LatLng(90, -180),
                };
            }
            config.opt.matrixIds = matrixIds;
            this.mapLayer.addLayer(WMTS(config.url, config.opt));
        }
        if (config.type == "dynamicMapLayer") {
            let envLayer = esri
                .dynamicMapLayer({
                    url: config.url,
                    opacity: config.opacity,
                    f: config.f,
                })
                .addTo(this.mapLayer);
            return envLayer;
        }
    };
    //   动态添加服务
    this.wmtAdd = function(Config) {
        var matrixIds = [];
        for (var i = 0; i < 21; ++i) {
            matrixIds[i] = {
                identifier: "" + (i + Config.identifier),
                topLeftCorner: new L.LatLng(90, -180),
            };
        }
        Config.opt.matrixIds = matrixIds;
        let wmtsobj = WMTS(Config.url, Config.opt).addTo(this.editLayer);
        return wmtsobj;
    };
    // 卷帘效果 skymapImage1 skymapImage2底图
    this.sideBySide = function(status) {
        if (this.mapSplitControl) {
            this.mapSplitControl.remove();
            this.mapSplitControl = null;
        } else {
            let this_ = this;
            let osmLayer = WMTS(
                config.skymapImage1.url,
                config.skymapImage1.opt
            ).addTo(this_.geowayMap);
            let stamenLayer = WMTS(
                config.skymapImage2.url,
                config.skymapImage2.opt
            ).addTo(this_.geowayMap);
            this_.mapSplitControl = L.control.sideBySide(osmLayer, stamenLayer);
            this_.mapSplitControl.addTo(this_.geowayMap);
        }
    };
    // 删除指定图层 removeLayer(marker)
    this.removeLayer = function(layer) {
        this.editLayer.removeLayer(layer);
        // this.geowayMap.removeLayer(layer)
    };
    // 删除geowayMap指定图层 removeLayer(marker)
    this.removeLayergeowayMap = function(layer) {
        this.geowayMap.removeLayer(layer);
        // this.geowayMap.removeLayer(layer)
    };
    // 删除mapLayer指定图层 removeLayer(marker)
    this.removeLayermapLayer = function(layer) {
        this.mapLayer.removeLayer(layer);
        // this.geowayMap.removeLayer(layer)
    };
    // 图片叠加
    this.imageOverlay = function(img, point1, point2, point3, isView) {
        let imageLayer = L.imageOverlay
            .rotated(img, point1, point2, point3, {
                opacity: 1,
                interactive: true,
                // attribution: ""
            })
            .addTo(this.editLayer);
        let bounds = new L.LatLngBounds(point1, point2).extend(point3);
        if (isView) {
            // let currentZoom = this.getMap().getBoundsZoom(geoJsonLayer.getBounds()); // 缩放比例
            // this.getMap().setView(center, currentZoom);
            this.getMap().fitBounds(bounds);
        }
 
        return imageLayer;
    };
    this.setGeoJsonView = function(geoJsonLayer) {
        this.getMap().fitBounds(geoJsonLayer.getBounds());
 
    };
    // 容器自适应 每次窗口大小改变后调用这个方法
    this.invalidateSize = function() {
        this.geowayMap.invalidateSize(true);
    };
    this.getRandomLatLng = function(num) {
        var bounds = num.getBounds(),
            //获取左下角坐标
            southWest = bounds.getSouthWest(),
            //获取右下角坐标
            northEast = bounds.getNorthEast(),
            //获取地图范围的长
            lngSpan = northEast.lng - southWest.lng,
            //获取地图范围的宽
            latSpan = northEast.lat - southWest.lat;
        return L.latLng(
            //返回任意地图范围内的x坐标
            southWest.lat + latSpan * Math.random(),
            //返回任意地图范围内的y坐标
            southWest.lng + lngSpan * Math.random()
        );
    };
    //  加载circleMarker
    this.circleMarkerPointer = function() {
        let _this = this;
        let content1 = "";
        let DefaultIcon = L.icon({
            iconUrl: icon,
            shadowUrl: iconShadow,
        });
        let layers = [];
        L.Marker.prototype.options.icon = DefaultIcon;
        for (let i = 0; i < 100; i++) {
            let numId = "mark" + i;
            let m = _this.getRandomLatLng(_this.geowayMap);
            let layer = new L.Marker(m);
            layers.push(layer);
            _this.markerGroups = L.layerGroup(layers);
            _this.editLayer.addLayer(_this.markerGroups);
            content1 =
                '<div style="width:260px;height:220px" id="' + numId + '"></div>';
            layer.bindPopup(content1, {});
            layer.on("popupopen", function(e) {
                let myChart = VCharts.init(document.getElementById(`${numId}`));
                let option = {
                    title: {
                        text: "测试",
                    },
                    tooltip: {},
                    legend: {
                        data: ["销量"],
                    },
                    xAxis: {
                        data: ["衬衫", "羊毛衫", "雪纺衫", "裤子"],
                    },
                    yAxis: {},
                    series: [{
                        name: "销量",
                        type: "bar",
                        data: [5, 20, 36, 10],
                    }, ],
                };
                myChart.clear(); //清除历史数据
                myChart.setOption({}); //清除历史数据
                myChart.setOption(option); //重绘数据
            });
        }
    };
    // 加载GeoJSON
    this.showGeoJSON = function() {
        let someFeatures = [{
                type: "Feature",
                properties: {
                    party: "Republican",
                    name: "三角形",
                },
                geometry: {
                    type: "Polygon",
                    coordinates: [
                        [
                            [116.3, 40],
                            [116.37, 40],
                            [116.34, 40.05],
                        ],
                    ],
                },
            },
            {
                type: "Feature",
                properties: {
                    party: "Democrat",
                    name: "矩形",
                },
                geometry: {
                    type: "Polygon",
                    coordinates: [
                        [
                            [116.22, 40],
                            [116.26, 40],
                            [116.26, 40.05],
                            [116.22, 40.05],
                        ],
                    ],
                },
            },
        ];
        let layGeo = L.geoJson(someFeatures, {
            style: {
                color: "#00f",
                weight: 3,
                opacity: 0.5,
            },
        });
        layGeo.addTo(this.geowayMap);
    };
    //平移地图到指定位置
    this.MoveToMap = function(center) {
        let py = L.latLng(center);
        // let currentZoom = this.getMap().getBoundsZoom(geoJsonLayer.getBounds()); // 缩放比例
        this.getMap().setView(center, 16);
    };
    //绘制图表至地图上
    /**
     * 加载图表信息,用得时候去调用就好
     * latings:位置信息
     * option:图表数据配置  可以去官网找例子  https://echarts.apache.org/examples/zh/index.html#chart-type-pie
     *
     */
    this.addEcharts = function(latings, echartsid, option) {
        latings = latings ? latings : [23.1301964, 113.2592945];
        // 通过marker实现任意样式
        var cMark1 = new L.marker(latings, {
            icon: L.divIcon({
                className: "leaflet-echart-icon",
                iconSize: [30, 30],
                html: `<div id="${echartsid}" style="width:30px;height:30px;position:relative;background-color:transparent;"></div>`,
            }),
        }).addTo(this.editLayer); //查看代码可知  editLayer是gwMap得编辑图层
        var myChart = VCharts.init(document.getElementById(echartsid));
 
        // myChart.clear() //清除历史数据
        // myChart.setOption({}) //清除历史数据
        myChart.setOption(option); //重绘数据
    };
};
export default GeowayMap;